package com.example.demo.config;

import com.example.demo.serivce.MyUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     *  注入我们自定义登录对象
     * @return
     */
    @Bean
    UserDetailsService userDetails(){
        return new MyUserDetailsService();
    }


    /**
     * 没有passwordEncoder会抛java.lang.IllegalArgumentException:
     *      There is no PasswordEncoder mapped for the id "null"
     *      注入我们的 密码加密 对象
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//表单登录
                .loginPage("/loginUser")// 定义当需要用户登录时候，转到的登录页面。
          .and()
           .authorizeRequests()//授权请求
                .antMatchers("/common").hasAnyRole("admin","user")//设置权限页面和授权角色
                .antMatchers("/admin").hasRole("admin") //设置admin路径只有admin才可以访问
                .antMatchers("/").permitAll()//首页直接通过
           .and()
          .exceptionHandling().accessDeniedPage("/noPermission") //如果当用户没有此权限我们就跳转到无权限页面
        ;
    }

}